package com.qiao.dfw.loggic.login;

import com.qiao.dfw.config.SpringBeanUtil;
import com.qiao.dfw.dao.PlayerMapper;
import com.qiao.dfw.entity.Player;
import com.qiao.dfw.entity.PlayerLocal;
import com.qiao.dfw.loggic.ATask;
import com.qiao.dfw.loggic.ECode;
import com.qiao.dfw.loggic.hall.MatchingTask;
import com.qiao.dfw.manager.LoggerManager;
import com.qiao.dfw.manager.MatchingManager;
import com.qiao.dfw.manager.PlayerManager;
import com.qiao.dfw.network.Connection;
import com.qiao.dfw.network.ConnectionManager;
import com.qiao.dfw.proto.Battle;
import com.qiao.dfw.proto.Login;
import com.qiao.dfw.proto.Role;
import com.qiao.dfw.thread.EThreadType;
import com.qiao.dfw.thread.ThreadManager;
import com.qiao.dfw.thread.ThreadTask;
import com.qiao.dfw.thread.Threads;

import java.util.Objects;


public class LoginTask extends ATask<Login.UserLoginRequest> {

    @Override
    public void execute0() {
        LoggerManager.info("收到 LoginTask %s,线程id: %s 对象 %s ", request.toString(), Thread.currentThread().getName(), this);
        long millis = System.currentTimeMillis();
        if (conn.player != null && millis - conn.player.lastLogin < 10 * 1000) {
            LoggerManager.info("10秒内已登录过一次,本次登录拒绝");
            return;
        }


        LoggerManager.info("开始查询数据库...logintask ");
        Player user = PlayerManager.get(request.getUsername());
        LoggerManager.info("查询数据库耗时: %s ", System.currentTimeMillis() - millis);

        if (user == null || !Objects.equals(request.getPassword(), user.password)) {
            // 密码错误
            Login.UserLoginResponse.Builder builder = Login.UserLoginResponse.newBuilder();
            builder.setSuccess(false);
            builder.setMsg("账号不存在/密码错误");
            sendMsg(builder.build().toByteArray());
            return;
        }

        // 检查是否在线,踢下线
        Connection connection = ConnectionManager.getNetConn(user.uid);
        if (connection != null && connection.player.local != PlayerLocal.Register) {
            conn.player = connection.player;
            // 顶号,踢下线
            Login.LeaveGameResponse.Builder builder = Login.LeaveGameResponse.newBuilder();
            Login.LeaveGameResponse build = builder.setCode(1).build();
            ATask.sendMsgToOne(connection.player.uid, ECode.LeaveGame, build.toByteArray());
            ConnectionManager.remove(connection.player.uid);
        } else {
            conn.player = user;
        }
        if (conn.player.local == PlayerLocal.Non || conn.player.local == PlayerLocal.Register) {
            conn.player.local = PlayerLocal.Login;
        }
        ConnectionManager.addNetConn(conn);
        // 登录成功了,检查玩家状态
        conn.player.lastLogin = millis;
        switch (conn.player.local) {
            case Login -> {
                enterHall(conn.player);
            }
            case Hall -> {
                enterHall(conn.player);
            }
            case Match -> {
                Threads thread = ThreadManager.getThreads(EThreadType.Match, 0);
                thread.push(new ThreadTask() {
                    @Override
                    public void execute() {
                        boolean leave = MatchingManager.leave(conn.player);
                        if (leave) {
                            enterHall(conn.player);
                        } else {
                            Threads thread = ThreadManager.getThreads(EThreadType.Battle, conn.player.room.threadId);
                            thread.push(new ThreadTask() {
                                @Override
                                public void execute() {
                                    enterBattle(conn.player);
                                }
                            });
                        }
                    }
                });
            }
            case Battle -> {
                if(conn.player.room == null){
                    enterHall(conn.player);
                }else {
                    Threads thread = ThreadManager.getThreads(EThreadType.Battle, conn.player.room.threadId);
                    thread.push(new ThreadTask() {
                        @Override
                        public void execute() {
                            enterBattle(conn.player);
                        }
                    });
                }
            }
        }

    }

    private void enterHall(Player user) {
        // 登录,初始化,跨日流程处理 等等
        Login.UserLoginResponse.Builder build = Login.UserLoginResponse.newBuilder();//user.build();
        Role.RoleInfo info = user.build();
        build.setRole(info);
        build.setSuccess(true);
        sendMsg(build.build().toByteArray());
        user.local = PlayerLocal.Hall;
    }

    private void enterBattle(Player user) {
        Role.MapData data = user.room.getBattleData(user);
        Login.UserLoginResponse.Builder build = Login.UserLoginResponse.newBuilder();
        Role.RoleInfo info = user.build();
        build.setRole(info);
        build.setData(data);
        build.setLoca(1);
        build.setSuccess(true);
        sendMsg(build.build().toByteArray());
        user.room.relink(user);
    }


    @Override
    public ECode getCode() {
        return ECode.Login;
    }

    public int getThreadIndex() {
        String username = request.getUsername();
        int hash = Objects.hash(username);
        return ThreadManager.getThreadIndex(EThreadType.Login, hash);
    }

}
